package com.wwwarehouse.usercenter.fragment.review;


import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.base.BaseApplication;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.activity.media.PreviewImageActivity;
import com.wwwarehouse.common.bean.media.UploadType;
import com.wwwarehouse.common.bean.response.CardDeskTaskResponseBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.UIWarningRelativeLayout;
import com.wwwarehouse.common.custom_widget.dialog.ConfirmDialogFragment;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.custom_widget.time_pick.DateUtil;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.ConvertUtils;
import com.wwwarehouse.common.tools.ToastUtils;
import com.wwwarehouse.usercenter.R;
import com.wwwarehouse.usercenter.bean.response.InviteInfoResponseBean;
import com.wwwarehouse.usercenter.bean.response.ReviewInviteeResponseBean;
import com.wwwarehouse.usercenter.constant.UserCenterConstant;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.wwwarehouse.usercenter.constant.UserCenterConstant.KEY_INVITE_CHECK_LIST;
import static com.wwwarehouse.usercenter.constant.UserCenterConstant.KEY_INVITE_CHECK_POSITION;


/**
 * Created by mundane on 2017/08/14.
 */
@Route(path = UserCenterConstant.PATH_REVIEW_INVITEE)
public class ReviewInviteeFragment extends BaseFragment implements View.OnClickListener {

	private TextView mTvName;
	private ImageView mIvIdCard;
	private ImageView mIvRegister;
	private UIWarningRelativeLayout mWarningViewName;
	private UIWarningRelativeLayout mWarningViewPhoto;
	private UIWarningRelativeLayout mWarningViewGender;
	private UIWarningRelativeLayout mWarningViewPhone;
	private UIWarningRelativeLayout mWarningViewLoaction;
	private UIWarningRelativeLayout mWarningViewInviteTime;
	private UIWarningRelativeLayout mWarningViewRegisterTime;
	private Button mBtnSubmit;
	public static final String BUNDLE_KEY = "bundle_key";
	private ImageView mIvMagnifier;
	private TextView mTvGender;
	private TextView mTvPhone;
	private TextView mTvLocation;
	private TextView mTvInviteDate;
	private TextView mTvRegisterDate;
	private List<UploadType> mUploadTypeList;
	private ReviewInviteeResponseBean mResponseBean;
	private String mCardUkid = "42060200000001463";
	public static final String KEY_CARD_UKID = "key_card_ukid";
	private StateLayout mStateLayout;
	private int ROUND_CORNER_RADIUS;
	// 待审核的集合
	private List<InviteInfoResponseBean.InviteDetailsBean> mInviteeList;
	// 在集合中的位置
	private int mCurrentPosition;

	private CardDeskTaskResponseBean.TaskBean mTaskDetails;

	public ReviewInviteeFragment() {
	}

	public static ReviewInviteeFragment newInstance() {
		ReviewInviteeFragment fragment = new ReviewInviteeFragment();
		Bundle args = new Bundle();
		fragment.setArguments(args);
		return fragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle bundle = getArguments();
		if (bundle != null) {

			mInviteeList = (List<InviteInfoResponseBean.InviteDetailsBean>) bundle.getSerializable(UserCenterConstant.KEY_INVITE_CHECK_LIST);
			mTaskDetails = (CardDeskTaskResponseBean.TaskBean) bundle.getSerializable(Constant.KEY_CARD_DESK_TASK_DETAILS);
			mCurrentPosition = bundle.getInt(KEY_INVITE_CHECK_POSITION);

			// 从站内通讯录进入审核联系人列表
			if (mInviteeList != null) {
				mCardUkid = mInviteeList.get(mCurrentPosition).getCardUkid();
			}

			// 从卡片桌面进入审核联系人列表
			if (mTaskDetails != null) {
				mCardUkid = mTaskDetails.getCardUkid();
			}
		}

		//预览图片
		mUploadTypeList = new ArrayList<>();
		for (int i = 0; i < 3; i++) {
			mUploadTypeList.add(new UploadType());
		}
		ROUND_CORNER_RADIUS = ConvertUtils.dip2px(getContext(), 1);


	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_review_invitee, container, false);
		return view;
	}

	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		boolean isFirstOpen = sp.getBooleanValue(TAG, true);
		if (isFirstOpen) {
			sp.putBooleanValue(TAG, false);
			GuideNewUserDialogFragment dialogFragment = GuideNewUserDialogFragment.newInstance();
			dialogFragment.setCancelable(false);
			dialogFragment.show(getFragmentManager(), "");
		}
		// findViewById
		mStateLayout = $(R.id.slt);
		mStateLayout.showProgressView(true);
		mTvName = $(R.id.tv_name);
		mTvName.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
		mTvGender = $(R.id.tv_gender);
		mTvPhone = $(R.id.tv_phone);
		mTvLocation = $(R.id.tv_location);
		mTvInviteDate = $(R.id.tv_invite_date);
		mTvRegisterDate = $(R.id.tv_register_date);
		mIvRegister = $(R.id.iv_idcard);
		mIvIdCard = $(R.id.iv_register);
		mIvMagnifier = $(R.id.iv_magnifier);
		mIvMagnifier.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				//预览图片
				Bundle bundle = new Bundle();
				bundle.putSerializable(Constant.KEY_UPLOAD_LIST, (Serializable) mUploadTypeList);
				bundle.putInt(Constant.kEY_UPLOAD_POSITION, 0);
				bundle.putString(Constant.KEY_PHOTO_VIEW_PREFIX, "http");
				// 是否禁止长按弹出弹窗? 是的
				bundle.putBoolean(Constant.KEY_FORBID_CLICK, true);
				startActivity(PreviewImageActivity.class, bundle, false);
			}
		});
		mWarningViewName = $(R.id.warning_view_name);
		mWarningViewPhoto = $(R.id.warning_view_photo);
		mWarningViewGender = $(R.id.warning_view_gender);
		mWarningViewPhone = $(R.id.warning_view_phone);
		mWarningViewLoaction = $(R.id.warning_view_location);
		mWarningViewInviteTime = $(R.id.warning_view_invite_time);
		mWarningViewRegisterTime = $(R.id.warning_view_register_time);
		mBtnSubmit = $(R.id.btn_submit);
	}

	private Bundle getBundle() {
		Bundle bundle = new Bundle();
		bundle.putParcelable(BUNDLE_KEY, mResponseBean);
		bundle.putString(KEY_CARD_UKID, mCardUkid);
		bundle.putSerializable(KEY_INVITE_CHECK_LIST, (Serializable) mInviteeList);
		bundle.putInt(KEY_INVITE_CHECK_POSITION, mCurrentPosition);
		return bundle;
	}

	private void changeButtonState() {
		if (isAllRight()) {
			mBtnSubmit.setBackgroundResource(R.drawable.common_btn1_press_shape);
			mBtnSubmit.setText("提交");
		} else {
			mBtnSubmit.setBackgroundResource(R.drawable.common_btn1_selector_yellow);
			mBtnSubmit.setText("审核不通过");
		}
	}

	// 是否需要重新邀请
	private boolean isRefused() {
		if (mResponseBean.inviteDate.checked) {
			return true;
		} else if (mResponseBean.name.checked) {
			return true;
		} else if (mResponseBean.registerCity.checked) {
			return true;
		} else if (mResponseBean.registerDate.checked) {
			return true;
		}
		return false;
	}

	private boolean isAllRight() {
		mResponseBean.name.checked = mWarningViewName.isWarning();
		mResponseBean.registerUrl.checked = mWarningViewPhoto.isWarning();
		if (mWarningViewPhoto.isWarning()) {
			mIvMagnifier.setVisibility(View.GONE);
		} else {
			mIvMagnifier.setVisibility(View.VISIBLE);
		}
		mResponseBean.personSex.checked = mWarningViewGender.isWarning();
		mResponseBean.mobile.checked = mWarningViewPhone.isWarning();
		mResponseBean.registerCity.checked = mWarningViewLoaction.isWarning();
		mResponseBean.inviteDate.checked = mWarningViewInviteTime.isWarning();
		mResponseBean.registerDate.checked = mWarningViewRegisterTime.isWarning();

		if (mResponseBean.faceUrl.checked) {
			return false;
		} else if (mResponseBean.inviteDate.checked) {
			return false;
		} else if (mResponseBean.mobile.checked) {
			return false;
		} else if (mResponseBean.name.checked) {
			return false;
		} else if (mResponseBean.personSex.checked) {
			return false;
		} else if (mResponseBean.registerCity.checked) {
			return false;
		} else if (mResponseBean.registerDate.checked) {
			return false;
		} else if (mResponseBean.registerUrl.checked) {
			return false;
		}
		return true;
	}


	@Override
	public void setTitle() {
		if (peekFragment() instanceof ReviewInviteeFragment) {
			mActivity.setTitle("审核被邀请人");
		}
	}

	@Override
	public void requestDatas() {
		Map<String, String> map = new HashMap<>();
		map.put("cardUkid", mCardUkid);
		NoHttpUtils.httpPost(UserCenterConstant.GET_AUDIT_INFO, map, onResponseListener, 0);
	}

	private final String TAG = "ReviewInviteeFragment";

	NoHttpUtils.OnResponseListener onResponseListener = new NoHttpUtils.OnResponseListener() {
		@Override
		public void onSucceed(CommonClass commonClass, int what) {
			switch (what) {
				case 0:
					if (TextUtils.equals("0", commonClass.getCode())) {
						mStateLayout.showContentView();
						mResponseBean = JSON.parseObject(commonClass.getData().toString(), ReviewInviteeResponseBean.class);
						BaseApplication.getApplicationInstance().displayRoundImgPixel(mResponseBean.faceUrl.inviteeInfo, mIvIdCard, ROUND_CORNER_RADIUS);
						BaseApplication.getApplicationInstance().displayRoundImgPixel(mResponseBean.registerUrl.inviteeInfo, mIvRegister, ROUND_CORNER_RADIUS);
						mUploadTypeList.get(0).setPath(mResponseBean.faceUrl.inviteeInfo);
						mUploadTypeList.get(1).setPath(mResponseBean.registerUrl.inviteeInfo);
						mTvName.setText(mResponseBean.name.inviteeInfo);
						mTvGender.setText(String.format("性别: %s", mResponseBean.personSex.inviteeInfo));
						mTvPhone.setText(String.format("手机: %s", mResponseBean.mobile.inviteeInfo));
						mTvLocation.setText(String.format(mResponseBean.registerCity.inviteeInfo));
						mTvInviteDate.setText(String.format("邀请: %s", mResponseBean.inviteDate.inviteeInfo));
						mTvRegisterDate.setText(String.format("注册: %s", mResponseBean.registerDate.inviteeInfo));
						mBtnSubmit.setOnClickListener(new View.OnClickListener() {
							@Override
							public void onClick(View v) {
								popFragment();
								if (isAllRight()) {
									pushFragment(ReviewPassFragment.newInstance(getBundle()));
								} else if (isRefused()) {
									pushFragment(ReviewRefuseFragment.newInstance(getBundle()));
								} else {
									pushFragment(ReviewFailFragment.newInstance(getBundle()));
								}
							}
						});
						mWarningViewName.setOnClickListener(ReviewInviteeFragment.this);
						mWarningViewPhoto.setOnClickListener(ReviewInviteeFragment.this);
						mWarningViewGender.setOnClickListener(ReviewInviteeFragment.this);
						mWarningViewPhone.setOnClickListener(ReviewInviteeFragment.this);
						mWarningViewLoaction.setOnClickListener(ReviewInviteeFragment.this);
						mWarningViewInviteTime.setOnClickListener(ReviewInviteeFragment.this);
						mWarningViewRegisterTime.setOnClickListener(ReviewInviteeFragment.this);

						String format = "yyyy-MM-dd HH:mm:ss";
						Date inviteDate = DateUtil.formatDateStr(mResponseBean.inviteDate.inviteeInfo, format);
						Date registerDate = DateUtil.formatDateStr(mResponseBean.registerDate.inviteeInfo, format);
						if (registerDate.before(inviteDate)) {
							Log.d(TAG, "时间有误");
						}
					} else {
						ToastUtils.showToast(commonClass.getMsg());
					}
					break;
			}
		}

		@Override
		public void onFailed(String result, int what) {
		}

		@Override
		public void onFinish(int what) {

		}
	};

	private void ShowDialog(String prompt, final UIWarningRelativeLayout warningView) {
		String content = String.format("由于%s出错的注册人, 将无法修改注册信息, 只能再次邀请后才能进系统。确定要标识%s出错吗?", prompt, prompt);
		ConfirmDialogFragment dialogFragment = ConfirmDialogFragment.newInstance();
		dialogFragment.setTitle(content)
				.setOnConfirmClickListener(new ConfirmDialogFragment.OnConfirmClickListener() {
					@Override
					public void onConfirmClick(View view) {
						warningView.setStateWarning(true);
						changeButtonState();
						popFragment();
						pushFragment(ReviewRefuseFragment.newInstance(getBundle()));
					}
				})
				.setOnCancelClickListener(new ConfirmDialogFragment.onCancelClickListener() {
					@Override
					public void onCancelClick(View view, DialogFragment dialog) {
						warningView.setStateWarning(false);
						changeButtonState();
					}
				});
		dialogFragment.show(getFragmentManager(), "");
	}

	private void reverseState(UIWarningRelativeLayout warningLayout) {
		if (warningLayout.isWarning()) {
			warningLayout.setStateWarning(false);
		} else {
			warningLayout.setStateWarning(true);
		}
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.warning_view_name) {
			reverseState(mWarningViewName);
			if (mWarningViewName.isWarning()) {
				ShowDialog(mResponseBean.name.unReason, mWarningViewName);
			}
		} else if (id == R.id.warning_view_photo) {
			reverseState(mWarningViewPhoto);
		} else if (id == R.id.warning_view_gender) {
			reverseState(mWarningViewGender);
		} else if (id == R.id.warning_view_phone) {
			reverseState(mWarningViewPhone);
		} else if (id == R.id.warning_view_location) {
			reverseState(mWarningViewLoaction);
			if (mWarningViewLoaction.isWarning()) {
				ShowDialog(mResponseBean.registerCity.unReason, mWarningViewLoaction);
			}
		} else if (id == R.id.warning_view_invite_time) {
			reverseState(mWarningViewInviteTime);
			if (mWarningViewInviteTime.isWarning()) {
				ShowDialog(mResponseBean.inviteDate.unReason, mWarningViewInviteTime);
			}
		} else if (id == R.id.warning_view_register_time) {
			reverseState(mWarningViewRegisterTime);
			if (mWarningViewRegisterTime.isWarning()) {
				ShowDialog(mResponseBean.registerDate.unReason, mWarningViewRegisterTime);
			}
		} else {
		}
		changeButtonState();
	}

}
